from django.shortcuts import render
from rest_framework import status

from rest_framework.generics import CreateAPIView, RetrieveAPIView, UpdateAPIView
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from rest_framework.views import APIView

from users.models import User
from . import serializers

# Create your views here.


class UserView(CreateAPIView):
    serializer_class = serializers.CreateUsersSerializer


class UsernameCountView(APIView):
    """用户名数量"""

    def get(self, request, username):
        count = User.objects.filter(username=username).count()

        data = {
            "username": username,
            "count": count
        }

        return Response(data)


class UserMobileCount(APIView):
    """用户手机号数量"""

    def get(self, request, mobile):
        count = User.objects.filter(mobile=mobile).count()

        data = {
            "mobile": mobile,
            "count": count
        }

        return Response(data)


class UserDetailView(RetrieveAPIView):
    """用户详情"""
    serializer_class = serializers.UserDetailSerializer
    permission_classes = [IsAuthenticated]

    def get_object(self):
        return self.request.user


class EmailView(UpdateAPIView):
    serializer_class = serializers.EmailSerializer
    permission_classes = [IsAuthenticated]

    def get_object(self):
        return self.request.user


class VerifyEmailView(APIView):
    """
    邮箱验证
    """

    def get(self,request):
        # 获取token
        token=request.query_params.get('token')

        if not token:
            return Response({'message':'缺少token'},status=status.HTTP_400_BAD_REQUEST)

        # 验证token
        user=User.check_verify_email_token(token)

        if user is None:
            return Response({'message':'链接地址无效'},status=status.HTTP_400_BAD_REQUEST)

        else:
            user.email_active=True
            user.save()
            return  Response({'message':'ok'})